package com.sherllinhe.gateway.config;

import com.sherllinhe.gateway.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 功能：
 * 作者：Sherllin He
 * 日期：2025/5/7 14:15
 */
@Slf4j
@Component
public class LoginMemberFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getURI().getPath();

        //排除不需要验证的路径
        if (path.contains("/admin")
//                ||path.contains("/confirm-order")
                ||path.contains("/member/member/send-code")
                ||path.contains("/member/member/login")
                ||path.contains("/member/admin/feign/ticket")
                ||path.contains("/hello")
                ||path.contains("/redis")
                ||path.contains("/business/kaptcha")
        ) {
            log.info("不需要token校验:{}",path);
            return chain.filter(exchange);
        }else{
            log.info("需要token校验:{}",path);
        }
        // 从请求头中获取token
        String token = exchange.getRequest().getHeaders().getFirst("token");
        log.info("token校验开始:{}",token);
        if(token==null||token.isEmpty()){
            log.info("token为空，请求被拦截");
            exchange.getResponse().setStatusCode(org.springframework.http.HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        // 验证token是否有效
        boolean validate = JwtUtil.validate(token);
        if(validate){
            log.info("token有效，请求被放行！");
            return chain.filter(exchange);
        }else{
            log.info("token无效，请求被拦截");
            exchange.getResponse().setStatusCode(org.springframework.http.HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
